/*
 * $Id: PictureLoader.java 204 2009-06-18 17:05:54Z meyer@alphatec.de $
 * 
 *
 * Copyright 2009 DeltaDesk
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package deltadesk.apps.pictureviewer.io;

import java.io.IOException;

import javax.imageio.ImageIO;

import deltadesk.apps.pictureviewer.data.FilePictureModel;
import deltadesk.apps.pictureviewer.data.Picture;
import deltadesk.apps.pictureviewer.util.concurrent.BaseStoppableThread;

/**
 * PictureLoader
 * 
 * @author Andreas Meyer
 * @version $Revision: 204 $
 */
public class PictureLoader extends BaseStoppableThread {
	
	/** The model. */
	private final FilePictureModel model;
	
	/** The current index in the model. */
	private int index;

	/** Flag if we need to load pictures. */
	private boolean needUpdate;
	
	
	/**
	 * Construct the loader.
	 * 
	 * @param model
	 */
	public PictureLoader(final FilePictureModel model) {
		
		this.model = model;
		
		setPriority(Thread.MIN_PRIORITY);
	}

	/**
	 * @see java.lang.Thread#run()
	 */
	@Override
	public void run() {
		
		while(isRunning()) {
			
			if(needUpdate) {
				
				System.out.println("Update");
				try {

					for(int i = -5; i<5;i++) {
						load(index+i);
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				
				needUpdate = false;
			}
			
			try {
				Thread.sleep(50);
			} catch (Exception e) {}
		} // end while
	}

	/**
	 * @param index the index to set
	 */
	public synchronized void setIndex(final int index) {
		
		this.index = index;
		needUpdate = true;
	}
	
	/**
	 * Load the specified picture.
	 * 
	 * @param idx
	 * @throws IOException
	 */
	private void load(final int idx) throws IOException {
		
		if(idx < 0 || idx >= model.getSize()) {
			return;
		}
		
		final Picture pic = model.getPicture(idx);
		if(pic.getImage() == null) {
			System.out.println("Load " + idx);
			pic.setImage(ImageIO.read(pic.getSource()));
		} // end if
	}

}
